<template>
  <div class="vue-container">
    <common-form
      ref="commonForm"
      :disabled="disabled"
      :options="options"
      @handlerClick="handlerClick"
      @advancedSearch="handlerQuery"
    >
      <template slot="advanced-content">
        <el-form ref="advancedForm" style="margin-top: 20px;" :model="queryForm" label-width="80px">
          <el-form-item label="任务状态">
            <el-select v-model="queryForm.jobStatus" clearable style="width: 100%;" placeholder="请选择任务状态">
              <el-option
                v-for="(item, index) in jobStatusList"
                :key="index"
                :label="item.label"
                :value="Number(item.code)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="queryForm.createTime"
              style="width: 100%;"
              type="datetimerange"
              placeholder="选择时间"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
        </el-form>
      </template>
    </common-form>
    <common-table
      :table-data="data"
      :columns="columns"
      :height="height"
      :current-page="queryForm.pageNum"
      :page-size="queryForm.pageSize"
      :total="totalPage"
      :loading="loading"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      @handleSelectionChange="handleSelectionChange"
    >
      <!-- 列表序号 -->
      <template #serialNumber="scope">
        <span>{{
          Number(scope.index + 1) + (queryForm.pageNum - 1) * queryForm.pageSize
        }}</span>
      </template>
      <!-- 执行指令  #0：触发补偿 ，1：触发1次 ，2：不触发 -->
      <template #instruction="scope">
        <template v-for="(item, index) in instructionList">
          <el-tag
            v-if="scope.row.instruction === Number(item.code)"
            :key="index"
          >{{ item.label }}</el-tag>
        </template>
      </template>
      <!-- 任务状态  #1：正常 ，2：暂停 -->
      <template #jobStatus="scope">
        <el-popconfirm
          v-permission="{ permission: 'ops:scheduled:task:change', disabled }"
          :title="scope.row.jobStatus == 1 ? '确定要暂停该任务吗？' : '确定要启动该任务吗？'"
          icon=""
          @confirm="popConfirm(scope.row)"
        >
          <el-switch
            slot="reference"
            v-model="scope.row.jobStatus"
            v-permission="{ permission: 'ops:scheduled:task:change', disabled }"
            :active-value="1"
            :inactive-value="2"
            @change="switchChange($event, scope.row)"
          />
        </el-popconfirm>
      </template>
      <!-- 创建时间 -->
      <template #createTime="scope">
        {{ scope.row.createTime | formatTime }}
      </template>
      <!-- 列表操作按钮 -->
      <template #operation="scope">
        <el-button
          v-throttle
          v-permission="'ops:scheduled:task:update'"
          :size="size"
          type="text"
          icon="el-icon-edit-outline"
          @click.stop="handlerSave(scope.row)"
        >编辑</el-button>
        <el-button
          v-throttle
          v-permission="'ops:scheduled:task:del'"
          :size="size"
          type="text"
          icon="el-icon-delete"
          class="danger-btn"
          @click.stop="handlerDel(funs['del'], scope.row)"
        >删除</el-button><br>
        <el-button
          v-throttle
          v-permission="'ops:scheduled:task:update'"
          :size="size"
          type="text"
          class="success-btn"
          @click.stop="handlerStart(scope.row)"
        >立即执行<i class="el-icon-caret-right" /></el-button>
        <el-button
          v-throttle
          v-permission="'log:task:log:page'"
          :size="size"
          type="text"
          icon="el-icon-notebook-2"
          class="warning-btn"
          @click.stop="handlerLog(scope.row)"
        >调度日志</el-button>
      </template>
    </common-table>
    <!-- 新增or编辑组件 -->
    <add-or-update ref="addOrUpdate" :obj="{ instructionList, jobStatusList, }" @ok="getList" />
    <el-dialog
      v-drag
      title="立即执行"
      :visible.sync="startVisible"
      width="450px"
    >
      <el-form
        ref="startForm"
        :show-message="false"
        :size="size"
        :model="startForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="任务名" prop="jobName">
          <el-input
            v-model.trim="startForm.jobName"
            :disabled="true"
            show-word-limit
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="执行次数" prop="count">
          <el-input-number
            v-model.trim="startForm.count"
            :min="1"
            :max="10"
            placeholder="请输入执行次数"
            style="width: 100%;"
            show-word-limit
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="执行间隔" prop="interval">
          <el-input
            v-model="startForm.interval"
            oninput="value=value.replace(/[^\d]/g,'')"
            clearable
            placeholder="请输入执行间隔"
            @blur="startForm.interval = $event.target.value"
          >
            <el-select slot="append" v-model="startForm.unit" style="width: 100px;">
              <el-option
                v-for="(item, index) in unitList"
                :key="index"
                :label="item.label"
                :value="Number(item.code)"
              />
            </el-select>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="startVisible = false">取 消</el-button>
        <el-button v-throttle type="primary" @click="startSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mixin } from '@/views/pages/mixin'
import AddOrUpdate from './components/save'
import { openPage } from '@/utils'
export default {
  name: 'ScheduledTask',
  components: {
    AddOrUpdate
  },
  mixins: [mixin],
  data() {
    return {
      instructionList: [], // 执行指令  #0：触发补偿 ，1：触发1次 ，2：不触发数组
      jobStatusList: [], // 任务状态  #1：正常 ，2：暂停数组
      unitList: [], // 执行间隔单位 #1：小时, 2：分钟, 3：秒, 4：毫秒
      startVisible: false,
      startForm: {}, // 立即执行表单
      rules: { // 立即执行表单校验
        count: [
          { required: true, message: '请输入执行次数', trigger: 'blur' }
        ],
        interval: [
          { required: true, message: '请输入执行间隔', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请选择执行间隔单位', trigger: 'blur' }
        ]
      },
      // 表头数组
      columns: [
        {
          type: 'selection',
          width: '60'
        },
        {
          prop: 'number',
          label: '序号',
          width: '70',
          type: 'slot',
          slotType: 'serialNumber'
        },
        {
          prop: 'jobName',
          align: 'center',
          label: '任务名'
        },
        {
          prop: 'jobGroup',
          align: 'center',
          label: '任务分组'
        },
        {
          prop: 'jobKey',
          align: 'center',
          label: '任务key'
        },
        {
          prop: 'cron',
          align: 'center',
          label: 'cron表达式'
        },
        {
          prop: 'jobStatus',
          align: 'center',
          type: 'slot',
          slotType: 'jobStatus',
          label: '任务状态'
        },
        {
          prop: 'sort',
          align: 'center',
          label: '排序'
        },
        {
          prop: 'createTime',
          align: 'center',
          type: 'slot',
          slotType: 'createTime',
          label: '创建时间'
        },
        {
          type: 'slot',
          prop: 'operation',
          label: '操作',
          width: '188',
          slotType: 'operation',
          align: 'center',
          fixed: 'right'
        }
      ],
      // 顶部表单按钮组
      options: [{
        type: 'button',
        icon: 'el-icon-refresh',
        handler: 'handlerRefresh',
        float: 'left',
        class: 'refreshBtn',
        text: '刷新'
      },
      {
        type: 'button',
        icon: 'el-icon-plus',
        handler: 'handlerSave',
        float: 'left',
        btnType: 'primary',
        permission: 'create',
        text: '新增'
      },
      {
        type: 'button',
        icon: 'el-icon-delete',
        handler: 'handlerDels',
        class: 'deleteBtn',
        permission: 'batch:del',
        text: '删除',
        float: 'left'
      },
      {
        type: 'button',
        handler: 'handlerAdvanced',
        permission: 'page',
        class: 'refreshBtn',
        advanced: true,
        float: 'right',
        text: '高级查询'
      },
      {
        type: 'button',
        handler: 'handlerReset',
        permission: 'page',
        float: 'right',
        class: 'infoBtn',
        text: '重置'
      },
      {
        type: 'button',
        handler: 'handlerQuery',
        permission: 'page',
        float: 'right',
        text: '查询',
        btnType: 'primary'
      },
      {
        type: 'search',
        handler: 'handlerQuery',
        permission: 'page',
        bindValue: '',
        float: 'right',
        label: 'keyword',
        placeholder: '输入关键字搜索'
      }
      ]
    }
  },
  async created() {
    // 通过全局方法取数据字典
    this.instructionList = await this.getDictInfo('scheduled_task_instruction')
    this.jobStatusList = await this.getDictInfo('scheduled_task_job_status')
    this.unitList = await this.getDictInfo('dict_unit')
  },
  methods: {
    // 状态切换触发
    switchChange(e, form) {
      form.jobStatus = e === 1 ? 2 : 1
    },
    // 确认暂停或启动
    popConfirm(form) {
      this.loading = true
      form.jobStatus = form.jobStatus === 1 ? 2 : 1
      this.funs['change'](form).then((res) => {
        if (form.jobStatus === 1) {
          this.$message.success('任务已启动')
        } else {
          this.$message.error('任务已暂停')
        }
      }).catch(e => {
        form.jobStatus = form.jobStatus === 1 ? 2 : 1
      }).finally(() => {
        this.loading = false
      })
    },
    // 立即执行按钮
    handlerStart(row) {
      this.startForm = {
        id: row.id,
        jobName: row.jobName,
        count: 1,
        interval: 10,
        unit: 3
      }
      this.startVisible = true
    },
    // 提交立即执行
    startSubmit() {
      this.$refs['startForm'].validate((valid, obj) => {
        if (valid) {
          this.funs['startNow'](this.startForm).then(res => {
            this.$message.success('执行成功')
            this.startVisible = false
          })
        } else {
          const field = []
          for (const key in obj) {
            field.push(obj[key][0].message)
          }
          this.$message.error(field[0])
          return false
        }
      })
    },
    // 调度日志
    handlerLog(row) {
      openPage('调度日志', `/log/task-log`, { taskId: row.id })
    }
  }
}
</script>
